package cn.itcast.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义全局过滤器，实现用户请求参数认证
 *注意：全局过滤器针对所有路由都生效
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    /**
     * 过滤逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求实力和响应实例
        ServerHttpRequest request = exchange.getRequest();//请求实例
        ServerHttpResponse response = exchange.getResponse();//相应实例

        //2.获取所有请求参数的集合
        MultiValueMap<String, String> queryParams = request.getQueryParams();

        //3.获取authorization参数
        String auth = queryParams.getFirst("authorization");

        //4.判断参数值如果不是admin，则响应403
        if(!"admin".equals(auth)){
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();//响应结束不放行
        }

        //5.如果参数值是admin，则放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;//过滤器执行优先级,值越小，优先级越高，越优先被执行
    }
}
